package com.ld.aspect;


import com.ld.anotation.PreAuth;
import com.ld.emun.ErrorCodeEnum;
import com.ld.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class PermissionAspect {
    // 通过 Pointcut 获取注解位置
    @Pointcut("@annotation(com.ld.anotation.PreAuth)")
    public void stringPointCut() {

    }

    // 增强处理
    @Around("stringPointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        /*
         * 获取当前http请求中的token
         * 解析token :
         * 1、token是否存在
         * 2、token格式是否正确
         * 3、token是否已过期（解析信息或者redis中是否存在）
         * */
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(ErrorCodeEnum.NO_AUTHORIZE);
        }
        /*
         * 获取注解的值，并进行权限验证:
         * redis 中是否存在对应的权限
         * redis 中没有则从数据库中获取权限
         * 数据空中没有，抛异常，非法请求，没有权限
         * */
        Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
        PreAuth preAuth = method.getAnnotation(PreAuth.class);
        String value = preAuth.value();
        if(!value.equals("aaa")){
            throw new BusinessException(ErrorCodeEnum.NO_AUTHORITY);
        }
        return proceedingJoinPoint.proceed();
    }


}
